package com.android.lovely

import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import com.android.lovely.manager.KVStore
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.coroutines.resume

object GoogleRefer {

    fun init() {
        if (KVStore.refers.isNotEmpty()) return
        applicationScope.launchSafety {
            val result: ReferrerDetails? = getReferrer()
            val installReferrer = result?.installReferrer ?: ""
            KVStore.refers = installReferrer
        }
    }

    private suspend inline fun getReferrer() = withTimeoutOrNull(9000) {
        return@withTimeoutOrNull suspendCancellableCoroutine {
            val client = InstallReferrerClient.newBuilder(appContext).build()
            client.startConnection(object : InstallReferrerStateListener {
                override fun onInstallReferrerSetupFinished(responseCode: Int) {
                    try {
                        when (responseCode) {
                            InstallReferrerClient.InstallReferrerResponse.OK -> {
                                onEnd(client.installReferrer)
                            }

                            else -> onEnd(null)
                        }
                    } catch (ignore: Exception) {
                    }
                }

                fun onEnd(refer: ReferrerDetails?) {
                    if (!it.isActive) return
                    it.resume(refer)
                    client.endConnection()
                }

                override fun onInstallReferrerServiceDisconnected() {
                    onEnd(null)
                }
            })
        }
    }
}